<template>
  <view class="page">
    <!-- 右上角的规则按钮 -->
    <view class="rule-button" @click="showModal">规则</view>

    <!-- 弹窗 -->
    <view v-if="isModalVisible" class="modal-overlay" @click="hideModal">
      <view class="modal" @click.stop>
        <text class="modal-content">本软件是由Dmitai成员的作业，现软件处于试行状态，由于用户的不确定性，所以没有做太多的验证功能，但是后期会做，不仅仅只有虚拟产品，现在注册就是老用户。<br><p></p>老用户1元区直接免费，后期会给你提升用户等级，如果等级为3，9.9及以下的免费，如果等级4，全场免费</text>
        <button class="modal-close" @click="hideModal">关闭</button>
      </view>
    </view>

    <view class="container">
      <!-- 判断用户是否已登录 -->
      <view v-if="isLoggedIn">
        <!-- 登录后的欢迎信息页面 -->
        <view class="welcome-page">
          <text class="welcome-message">欢迎: {{ username }}</text><br>
          <text class="welcome-message">用户等级: {{ leve }} </text><br>
          <text class="welcome-message">余额: ￥{{ balance }} </text>
          <button @click="logout" class="logout-btn">退出登录</button>
        </view>
        <br><br>
        <!-- 商品展示 -->
        <view class="product-list">
          <view v-for="product in products" :key="product.id" class="product-item">
            <text class="product-name">{{ product.name }}</text><br>
			<img :src="product.image_url" alt="Product-Image" style="width: 200px; height: 200px; border-radius: 10px;"><br>

			
			<text class="product-description">商品描述：{{ product.description }}</text><br>
			<text class="product-stock">库存：{{ product.stock }}</text><br>
			

            <text class="product-price">￥{{ product.price }}</text>
            <!-- 只有登录后并且商品价格不为 0 时，才显示购买按钮 -->
            <button   class="purchase-btn" @click="purchase(product)">立即购买</button>
          </view>
        </view>
      </view>

      <!-- 未登录显示登录和注册表单 -->
      <view v-else>
        <view class="form">
          <view v-if="isLogin">
            <!-- 登录表单 -->
            <view class="input-group">
              <text class="label">用户名</text>
              <input v-model="username" class="input" type="text" placeholder="请输入用户名" />
            </view>

            <view class="input-group">
              <text class="label">密码</text>
              <input v-model="password" class="input" type="password" placeholder="请输入密码" />
            </view>

            <button class="login-btn" @click="handleLogin">登录</button>

            <view v-if="errorMessage" class="error-message">
              <text>{{ errorMessage }}</text>
            </view>

            <view class="switch-auth">
              <text @click="toggleAuth">没有账号? 注册</text>
            </view>
          </view>

          <!-- 注册表单 -->
          <view v-else>
            <view class="input-group">
              <text class="label">用户名</text>
              <input v-model="username" class="input" type="text" placeholder="请输入用户名" />
            </view>

            <view class="input-group">
              <text class="label">密码</text>
              <input v-model="password" class="input" type="password" placeholder="请输入密码" />
            </view>

            <button class="register-btn" @click="handleRegister">注册</button>

            <view v-if="errorMessage" class="error-message">
              <text>{{ errorMessage }}</text>
            </view>

            <view class="switch-auth">
              <text @click="toggleAuth">已有账号? 登录</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      isModalVisible: false, 
      errorMessage: '',  
      username: '',  
      password: '',  
      isLogin: true,  
      isLoggedIn: false,  
      level: '',  // Changed from 'leve' to 'level'
      banStatus: false,  
      banMessage: '',  
      balance: 0,  
      loginInterval: null,  
      products: [],  
    };
  },

  computed: {
    storedUsername() {
      return uni.getStorageSync('username');
    }
  },

  watch: {
    storedUsername(newVal) {
      this.isLoggedIn = !!newVal;
      this.username = newVal || '';  
    }
  },

  methods: {
    showModal() {
      this.isModalVisible = true;
    },
    
    hideModal() {
      this.isModalVisible = false;
    },

    handleLogin() {
      this.errorMessage = '';
    
      if (!this.username || !this.password) {
        this.errorMessage = '用户名和密码不能为空';
        return;
      }
    
      uni.request({
        url: 'https://api.dmitai.vip/login',
        method: 'POST',
        data: { username: this.username, password: this.password },
        success: (res) => {
          if (res.data.success) {
            uni.setStorageSync('token', res.data.token);
            uni.setStorageSync('username', this.username);
            this.isLoggedIn = true;
            this.fetchUserLevel();
            this.fetchUserStatus();
            this.fetchUserBalance();
            this.errorMessage = '';
            uni.showToast({ title: '登录成功', icon: 'success', duration: 2000 });
          } else {
            this.errorMessage = res.data.message || '登录失败';
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.errorMessage = '请求失败，请稍后重试';
        }
      });
    },

    fetchUserLevel() {
      uni.request({
        url: 'https://api.dmitai.vip/getUserLevel',
        method: 'GET',
        data: { username: this.username },
        success: (res) => {
          this.level = res.data.success ? res.data.level : '未知';
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.level = '未知';
        }
      });
    },

    fetchUserStatus() {
      uni.request({
        url: 'https://api.dmitai.vip/getUserStatus',
        method: 'GET',
        data: { username: this.username },
        success: (res) => {
          if (res.data.success) {
            if (res.data.isBanned) {
              this.banStatus = true;
              this.banMessage = res.data.description || '你已被封号，请联系管理员'; // Corrected field name to 'description'
              this.errorMessage = this.banMessage;
              this.logout();
              uni.showModal({
                title: '封号通知',
                content: this.banMessage,
                showCancel: false,
                confirmText: '知道了',
                success: () => {
                  uni.redirectTo({ url: '/pages/login/login' });
                }
              });
            } else {
              this.banStatus = false;
              this.banMessage = '';
              this.errorMessage = '';
            }
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.errorMessage = '请求失败，请稍后重试';
        }
      });
    },

    fetchUserBalance() {
      uni.request({
        url: 'https://api.dmitai.vip/getUserBalance',
        method: 'GET',
        data: { username: this.username },
        success: (res) => {
          this.balance = res.data.success ? res.data.balance : 0;
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.balance = 0;
        }
      });
    },

    handleRegister() {
      this.errorMessage = '';
      if (!this.username || !this.password) {
        this.errorMessage = '用户名和密码不能为空';
        return;
      }

      uni.request({
        url: 'https://api.dmitai.vip/register',
        method: 'POST',
        data: { username: this.username, password: this.password },
        success: (res) => {
          if (res.data.success) {
            uni.showToast({ title: '注册成功', icon: 'success' });
            this.toggleAuth();
          } else {
            this.errorMessage = res.data.message || '注册失败';
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.errorMessage = '请求失败，请稍后重试';
        }
      });
    },

    toggleAuth() {
      this.isLogin = !this.isLogin;
      this.username = '';
      this.password = '';
      this.errorMessage = '';
    },

    logout() {
      uni.removeStorageSync('token');
      uni.removeStorageSync('username');
      uni.showToast({ title: '退出成功', icon: 'success' });
      this.isLoggedIn = false;
    },

    checkLoginStatus() {
      this.loginInterval = setInterval(() => {
        const storedUsername = uni.getStorageSync('username');
        this.isLoggedIn = !!storedUsername;
        this.username = storedUsername || '';
        if (this.isLoggedIn) {
          this.fetchUserLevel();
          this.fetchUserStatus();
          this.fetchUserBalance();
          this.fetchProducts();
        }
      }, 10000);
    },

    fetchProducts() {
      uni.request({
        url: 'https://api.dmitai.vip/product', 
        method: 'GET',
        success: (res) => {
          if (res.data.success) {
            console.log('所有商品数据:', res.data.products);
    
            // 过滤出 is_zero_price = 1 的商品
            this.products = res.data.products.filter(product => product.is_zero_price === 1);
    
            if (this.products.length === 0) {
              uni.showToast({
                title: '没有符合条件的商品',
                icon: 'none',
                duration: 2000
              });
            }
          } else {
            uni.showToast({
              title: '获取商品失败',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          uni.showToast({
            title: '请求失败，请稍后重试',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },

   purchase(product) {
     // 检查库存是否足够
     if (product.stock <= 0) {
       uni.showToast({
         title: '库存不足，购买失败',
         icon: 'none',
         duration: 2000
       });
       return; // 如果库存不足，直接返回
     }
   
     // 检查余额是否足够
     if (this.balance < product.price) {
       uni.showToast({
         title: '余额不足，购买失败',
         icon: 'none',
         duration: 2000
       });
       return; // 如果余额不足，直接返回
     }
   
     // 如果库存和余额都足够，发起请求
     uni.request({
       url: 'https://api.dmitai.vip/shopping_list', 
       method: 'POST',
       data: {
         username: this.username,
         product_id: product.id,
         product_name: product.name, // 商品名称
         quantity: 1,  // 假设每次购买一个商品
       },
       success: (res) => {
         if (res.data.success) {
           uni.showToast({
             title: '购买成功',
             icon: 'success',
             duration: 2000
           });
   
           // 更新库存（如果有前端逻辑处理）
           product.stock -= 1;
   
           // 更新余额（如果有前端余额更新逻辑）
           this.balance -= product.price;
         } else {
           uni.showToast({
             title: '添加购物车失败',
             icon: 'none',
             duration: 2000
           });
         }
       },
       fail: (err) => {
         console.error('请求失败:', err);
         uni.showToast({
           title: '请求失败，请稍后重试',
           icon: 'none',
           duration: 2000
         });
       }
     });
   }},

  mounted() {
    const storedUsername = uni.getStorageSync('username');
    this.username = storedUsername || '';
    this.isLoggedIn = !!storedUsername;
    if (this.isLoggedIn) {
      this.fetchUserLevel();
      this.fetchUserStatus();
      this.fetchUserBalance();
    }

    this.checkLoginStatus();
    this.fetchProducts();
  },

  beforeDestroy() {
    if (this.loginInterval) {
      clearInterval(this.loginInterval);
    }
  }
}
</script>



<style scoped>
/* 整个页面 */
.page {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  padding: 20px;
  background-color: #f0f2f5; /* 更符合Facebook的淡灰色背景 */
  height: 100vh;
  font-family: 'Helvetica Neue', Arial, sans-serif; /* Facebook风格的字体 */
}

/* 弹窗遮罩层 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: #ffffff;
  border-radius: 20px;
  padding: 30px;
  max-width: 80%;
  box-shadow: 0px 10px 20px rgba(0, 0, 0, 0.1);
  text-align: center;
  transition: all 0.3s ease-in-out;
}

.modal-content {
  font-size: 16px;
  color: #333;
  margin-bottom: 20px;
  line-height: 1.5;
}

.modal-close {
  background-color: #1877f2; /* Facebook 蓝色 */
  color: white;
  padding: 12px 20px;
  border-radius: 25px;
  border: none;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.modal-close:hover {
  background-color: #005bb5; /* 更深的蓝色 */
}

/* 规则按钮 */
.rule-button {
  position: absolute;
  top: 20px;
  right: 20px;
  background-color: #1877f2;
  color: white;
  padding: 10px 18px;
  border-radius: 25px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.rule-button:hover {
  background-color: #005bb5;
}

/* 登录与注册表单 */
.form {
  background: #ffffff;
  border-radius: 20px;
  padding: 30px 20px;
  box-shadow: 0px 10px 20px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
  text-align: center;
}

.input-group {
  margin-bottom: 20px;
}

.label {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.input {
  width: 90%;
  padding: 12px 16px;
  margin-top: 8px;
  border-radius: 12px;
  border: 1px solid #d1d1d6;
  background-color: #f7f7f8;
  color: #1c1c1e;
  font-size: 16px;
}

.login-btn, .register-btn {
  width: 100%;
  padding: 14px;
  background-color: #1877f2;
  color: white;
  font-size: 18px;
  border-radius: 25px;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.login-btn:hover, .register-btn:hover {
  background-color: #005bb5;
}

.error-message {
  color: #ff3b30;
  font-size: 14px;
  margin-top: 10px;
  text-align: center;
}

.switch-auth {
  text-align: center;
  color: #1877f2;
  font-size: 14px;
  cursor: pointer;
}

.switch-auth:hover {
  text-decoration: underline;
}

/* 欢迎页面 */
.welcome-page {
  background: #ffffff;
  border-radius: 20px;
  padding: 30px;
  width: 100%;
  align-items: center;
  max-width: 400px;
  box-shadow: 0px 10px 20px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.welcome-message {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
  font-weight: 600;
}

.logout-btn {
  background-color: #ff3b30;
  color: white;
  padding: 14px 20px;
  border-radius: 25px;
  font-size: 16px;
  cursor: pointer;
  border: none;
  transition: background-color 0.3s ease;
}

.logout-btn:hover {
  background-color: #c1351d;
}

/* 商品列表 */
.product-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 30px;
  background: linear-gradient(135deg, #f7f7f7, #dfe9f3); /* 更柔和的渐变背景 */
}

/* 每个商品项 */
.product-item {
  width: 100%;
  max-width: 350px;
  margin: 20px;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  text-align: center;
  backdrop-filter: blur(8px);
  transition: transform 0.3s ease, box-shadow 0.3s ease, background-color 0.3s ease;
  font-family: 'Arial', sans-serif;
  position: relative;
  overflow: hidden;
}

/* 商品图片 */
.Product-Image {
  width: 100%;
  height: 250px;
  border-radius: 12px;
  object-fit: cover;
  margin-bottom: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

/* 商品名称 */
.product-name {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  letter-spacing: 1px;
  font-family: 'Montserrat', sans-serif;
}

/* 商品描述 */
.product-description {
  font-size: 14px;
  color: #999;
  margin-bottom: 12px;
  line-height: 1.6;
  font-style: italic;
  letter-spacing: 0.5px;
}

/* 商品库存 */
.product-stock {
  font-size: 14px;
  color: #b0b0b0;
  margin-bottom: 18px;
  letter-spacing: 0.5px;
}

/* 商品价格 */
.product-price {
  font-size: 20px;
  color: #1877f2;
  font-weight: bold;
  margin-bottom: 25px;
  letter-spacing: 1px;
}

/* 立即购买按钮 */
.purchase-btn {
  background-color: #1877f2;
  color: white;
  padding: 12px 25px;
  font-size: 18px;
  font-weight: 600;
  border: none;
  border-radius: 30px;
  cursor: pointer;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transition: transform 0.3s ease, background-color 0.3s ease, box-shadow 0.3s ease;
  letter-spacing: 1px;
}

/* 按钮悬停效果 */
.purchase-btn:hover {
  background-color: #1566c0;
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

/* 按钮点击效果 */
.purchase-btn:active {
  transform: translateY(0);
  background-color: #105fa6;
}

/* 商品项悬停效果 */
.product-item:hover {
  transform: translateY(-10px);
  box-shadow: 0 12px 35px rgba(0, 0, 0, 0.15);
  background-color: rgba(255, 255, 255, 1);
}

/* 商品项悬停时图片动画 */
.product-item:hover .Product-Image {
  transform: scale(1.05);
}

</style>
